from flask import Blueprint, jsonify, request
from src.models.user import Circle, CircleMember, User, db
from datetime import datetime
import uuid

circle_bp = Blueprint('circle', __name__)

@circle_bp.route('/circles', methods=['POST'])
def create_circle():
    """创建圈子"""
    data = request.json
    name = data.get('name')
    description = data.get('description', '')
    creator_id = data.get('creator_id')
    
    if not name or not creator_id:
        return jsonify({'error': '圈子名称和创建者ID不能为空'}), 400
    
    # 检查创建者是否存在
    creator = User.query.get(creator_id)
    if not creator:
        return jsonify({'error': '创建者不存在'}), 404
    
    # 创建圈子
    circle = Circle(
        name=name,
        description=description,
        creator_id=creator_id,
        invite_code=str(uuid.uuid4())
    )
    db.session.add(circle)
    db.session.flush()  # 获取circle.id
    
    # 将创建者添加为管理员
    member = CircleMember(
        circle_id=circle.id,
        user_id=creator_id,
        role='admin'
    )
    db.session.add(member)
    db.session.commit()
    
    return jsonify(circle.to_dict()), 201

@circle_bp.route('/circles/<int:circle_id>', methods=['GET'])
def get_circle(circle_id):
    """获取圈子详情"""
    circle = Circle.query.get_or_404(circle_id)
    if not circle.is_active:
        return jsonify({'error': '圈子已解散'}), 404
    
    # 获取成员信息
    members = db.session.query(CircleMember, User).join(User).filter(
        CircleMember.circle_id == circle_id,
        CircleMember.is_active == True
    ).all()
    
    member_list = []
    for member, user in members:
        member_info = member.to_dict()
        member_info['user'] = user.to_dict()
        member_list.append(member_info)
    
    circle_info = circle.to_dict()
    circle_info['members'] = member_list
    
    return jsonify(circle_info)

@circle_bp.route('/circles/join', methods=['POST'])
def join_circle():
    """通过邀请码加入圈子"""
    data = request.json
    invite_code = data.get('invite_code')
    user_id = data.get('user_id')
    
    if not invite_code or not user_id:
        return jsonify({'error': '邀请码和用户ID不能为空'}), 400
    
    # 查找圈子
    circle = Circle.query.filter_by(invite_code=invite_code, is_active=True).first()
    if not circle:
        return jsonify({'error': '邀请码无效或圈子已解散'}), 404
    
    # 检查用户是否存在
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    # 检查是否已经是成员
    existing_member = CircleMember.query.filter_by(
        circle_id=circle.id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if existing_member:
        return jsonify({'error': '您已经是该圈子的成员'}), 400
    
    # 添加成员
    member = CircleMember(
        circle_id=circle.id,
        user_id=user_id,
        role='member'
    )
    db.session.add(member)
    db.session.commit()
    
    return jsonify({
        'message': '成功加入圈子',
        'circle': circle.to_dict()
    })

@circle_bp.route('/circles/<int:circle_id>/leave', methods=['POST'])
def leave_circle():
    """退出圈子"""
    data = request.json
    user_id = data.get('user_id')
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 查找成员记录
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 404
    
    # 检查是否是管理员
    if member.role == 'admin':
        # 检查是否还有其他管理员
        other_admins = CircleMember.query.filter_by(
            circle_id=circle_id,
            role='admin',
            is_active=True
        ).filter(CircleMember.user_id != user_id).count()
        
        if other_admins == 0:
            return jsonify({'error': '您是唯一的管理员，请先转让管理权限或解散圈子'}), 400
    
    # 标记为非活跃状态
    member.is_active = False
    db.session.commit()
    
    return jsonify({'message': '成功退出圈子'})

@circle_bp.route('/circles/<int:circle_id>/kick', methods=['POST'])
def kick_member():
    """踢出成员"""
    data = request.json
    admin_id = data.get('admin_id')
    target_user_id = data.get('target_user_id')
    
    if not admin_id or not target_user_id:
        return jsonify({'error': '管理员ID和目标用户ID不能为空'}), 400
    
    # 检查操作者是否是管理员
    admin_member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=admin_id,
        role='admin',
        is_active=True
    ).first()
    
    if not admin_member:
        return jsonify({'error': '您没有管理权限'}), 403
    
    # 查找目标成员
    target_member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=target_user_id,
        is_active=True
    ).first()
    
    if not target_member:
        return jsonify({'error': '目标用户不是该圈子的成员'}), 404
    
    # 不能踢出管理员
    if target_member.role == 'admin':
        return jsonify({'error': '不能踢出管理员'}), 400
    
    # 标记为非活跃状态
    target_member.is_active = False
    db.session.commit()
    
    return jsonify({'message': '成功踢出成员'})

@circle_bp.route('/circles/<int:circle_id>/dissolve', methods=['POST'])
def dissolve_circle():
    """解散圈子"""
    data = request.json
    admin_id = data.get('admin_id')
    
    if not admin_id:
        return jsonify({'error': '管理员ID不能为空'}), 400
    
    # 检查操作者是否是管理员
    admin_member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=admin_id,
        role='admin',
        is_active=True
    ).first()
    
    if not admin_member:
        return jsonify({'error': '您没有管理权限'}), 403
    
    # 解散圈子
    circle = Circle.query.get_or_404(circle_id)
    circle.is_active = False
    
    # 将所有成员标记为非活跃状态
    CircleMember.query.filter_by(circle_id=circle_id).update({'is_active': False})
    
    db.session.commit()
    
    return jsonify({'message': '圈子已解散'})

@circle_bp.route('/users/<int:user_id>/circles', methods=['GET'])
def get_user_circles(user_id):
    """获取用户参与的所有圈子"""
    # 查询用户参与的活跃圈子
    circles = db.session.query(Circle, CircleMember).join(CircleMember).filter(
        CircleMember.user_id == user_id,
        CircleMember.is_active == True,
        Circle.is_active == True
    ).all()
    
    circle_list = []
    for circle, member in circles:
        circle_info = circle.to_dict()
        circle_info['user_role'] = member.role
        circle_info['joined_at'] = member.joined_at.isoformat() if member.joined_at else None
        circle_list.append(circle_info)
    
    return jsonify(circle_list)

